<?php

/**
 * 用户模型
 */

namespace app\api\model;


use app\api\controller\Bind;
use app\api\controller\Config;
use app\common\lib\RedisKey;
use app\common\lib\RespCode;
use app\common\model\BaseModel;
use custom\Err;
use custom\Log;
use custom\Redis;
use custom\Token;
use oss\Oss;
use PDOStatement;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Model;

class CompanyAgent extends BaseModel {

    /**
     * 获取用户详情
     * @param $uid
     * @param string $field
     * @return array|PDOStatement|string|Model|null
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getInfo($uid, $field = '*') {
        return Db::name ('company_agent')->where (['id' => $uid])->where (['deleted' => 0])->field ($field)->find ();
    }


    /**
     * 校验账号登录（app）
     * @param $params
     * @param $headers
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     * @throws PDOException
     */
    public static function checkAgentUser($params, $headers) {
        //查询账号数据
        $data = Db::name ('company_agent')
            ->alias('a')
            ->field("a.*,b.default_city_code,b.applets_id,b.wechat_appid,b.wechat_secret,b.app_logo,b.wechat_version")
            ->join('erp_company b','a.company_id=b.id')
            ->where ('a.phone', $params['phone'])
            ->where ('b.deleted', 0)
            ->where ('a.deleted', 0)
            ->find();
        if (!$data){
            Err::add('非会员账号',RespCode::NO_MEMBERS_LOGING);
            return false;
        }else{
            //有账号数据（1.先更新数据，2.获取参数返回）
            //清除极光推送标识
            self::clearRegistrationid ($headers['registrationid']);
            $update['registration_id']=$headers['registrationid'];//极光推送设备唯一标识
            $update['os']=$headers['os'];//设备类型：1ios、2安卓
            $update['version']=$headers['version'];//版本号
            $update['en_key']=get_nonce_str(16);//16位随机字符串

            //更新账号数据
            Db::name("company_agent")
                ->where('phone', $params['phone'])
                ->update($update);
            $uid = $data['id'];
            $avatar = $data['cover'];//头像
            $account = $data['phone'];//手机号
            $is_push = $data['is_push'];//推送状态
            $company_id = $data['company_id'];//公司id
            $applets_id = $data['applets_id'];//小程序原始id
            $wechat_appid = $data['wechat_appid'];//开放平台appid
            $wechat_secret = $data['wechat_secret'];//开放平台密钥key
            $app_logo = $data['app_logo'];//公司applogo
            $wechat_version = $data['wechat_version'];//小程序版本 1正式版本 2体验版本
            //公司城市code
//            $reg_code=Db::name('company')->where('id',$data['company_id'])->where('deleted',0)->value('default_city_code');
            if ($data['company_shop_id']){
                //门店默认房源城市
                $reg_code=db('company_shop')->where('id',$data['company_shop_id'])->where('deleted',0)->value('city_code');
            }else{
                $reg_code=$data['default_city_code'];
            }


            $city_codes=$reg_code?explode('-',$reg_code):[];
            //是否有定制需求
            if (empty(AgentDemand::getMycount($uid))) {
                $is_demand = 0;
            } else {
                $is_demand = 1;
            }
            //获取token
            $Token = new Token();
            $token_ = $Token->getToken ($uid, $headers,Token::API_TOKEN, Token::EXPIRE_TIME, RedisKey::APP_TOKEN_HASH);
            $mainid = md5 (md5 ($uid));
            $city_code=isset($city_codes[0])?$city_codes[0]:'';
            $city_name=isset($city_codes[1])?$city_codes[1]:'';
            $region=db('region')->field('x(location) as lng,Y(location) as lat')->where("city_code={$city_code}")->find();
            //参数组装
            $re=['token' => $token_,
                'avatar' => empty($avatar) ? config('global.default_avt') : $avatar,//头像
                'account' => $account,
                'id' => $mainid,
                'is_push' => $is_push,
                'is_demand' => $is_demand,
                'city_code'=>$city_code,
                'city_name'=>$city_name,
                'company_id'=>$company_id,
                'agent_id'=>$uid,
                'lng'=>isset($region['lng'])?$region['lng']:0,
                'lat'=>isset($region['lat'])?$region['lat']:0,
                'applets_id'=>$applets_id,
                'com_id'=>$wechat_appid,
                'com_key'=>$wechat_secret,
                'en_key'=>$update['en_key'],
                'app_logo'=>$app_logo,
                'wechat_version'=>$wechat_version
            ];
            return $re;
        }

    }


    /**
     * 清楚匹配$registrationid的用户
     * @param $registrationid
     * @throws Exception
     * @throws PDOException
     */
    public static function clearRegistrationid($registrationid) {
        Db::name ("company_agent")
            ->where ('registration_id', $registrationid)
            ->update (['registration_id' => '']);
    }

    /**
     * 审核版本创建测试数据
     * @param $params
     * @param $headers
     */
    public static function createAgentUser($params,$headers){
        //公司获取默认公司
        $company_id=config('global.audit_def_companyid');
        //company_agent表数据
        $add_agent['company_id']=$company_id;//公司id
        $add_agent['company_shop_id']=0;//门店id
        $add_agent['template_id']=1;//名片模板id 1：大气版，2：商务版，3：黑金版，4：仰望版，5：简约版
        $add_agent['cover']='https://oss.fpaiyun.com/badmin/agent_cover/2020-11-18/32j2irhadtx2.jpg';//头像
        $add_agent['name']=$params['phone'];//名称
        $add_agent['phone']=$params['phone'];//电话
        $add_agent['email']='';//邮箱
        $add_agent['position']='未知';//职位
        $add_agent['wechat']='';//微信号
        $add_agent['school_name']='';//学校名称
        $add_agent['school_id']=0;//学校id
        $add_agent['education']=0;//学历：1高中、2大专、3本科、4硕士、5博士、6其它
        $add_agent['wechat_code']='';//小程序二维码
        $add_agent['major']='';//专业
        $add_agent['school_s_time']=0;//在校开始时间
        $add_agent['school_e_time']=0;//在校结束时间
        $add_agent['province']='';//省
        $add_agent['city']='';//市
        $add_agent['area']='';//区
        $add_agent['address']='';//详细地址
        $add_agent['greetings']='';
        $add_agent['city_codes']='';//城市code
        $add_agent['describe']='';//自我描述
        $add_agent['label']='';//标签
        $add_agent['voice']='';//语音
        $add_agent['voice_time']=0;//语音时长
        $add_agent['pics']='';//我的图片
        $add_agent['os']=$headers['os'];//设备类型：1ios、2安卓
        $add_agent['version']=$headers['version'];//版本号
        $add_agent['registration_id']=$headers['registrationid'];//极光推送设备唯一标识
        $add_agent['is_push']=1;//是否接收推送信息：0否、1是。默认1
        $add_agent['is_customer']=0;//是否是客服：0否、1是。默认1
        $add_agent['itime']=strtotime('-1 day');//添加时间
        $add_agent['utime']=strtotime('-1 day');//操作时间
        $add_agent['deleted']=0;//0:未删除 1：已删除
        $add_agent['is_audit']=1;//1：审核状态创建 ；0：正常数据
        $add_agent['en_key']=get_nonce_str(16);//16位随机字符串
        $agent_id=db('company_agent')->insertGetId($add_agent);
        $url= self::createWechatCode($company_id,$agent_id);
        db('company_agent')->where("id={$agent_id}")->update(['wechat_code'=>$url]);

        //company_user表数据
        $add_user1['company_id']=$company_id;//公司id
        $add_user1['agent_id']=$agent_id;//经纪人id
        $add_user1['unionid']='';//unionid
        $add_user1['openid']='';//小程序openid
        $add_user1['nickname']='5bCP5piO';//昵称
        $add_user1['cover']='https://oss.fpaiyun.com/badmin/agent_cover/2020-11-18/32j2irhadtx2.jpg';//头像
        $add_user1['itime_exclusive']=0;//专属客户时间
        $add_user1['daytime_exclusive']=0;//专属客户时间（y-m-d）
        $add_user1['itime_potential']=strtotime('-1 day');//潜在客户时间
        $add_user1['daytime_potential']=strtotime(date('Y-m-d',strtotime('-1 day')));//潜在客户时间（y-m-d）
        $add_user1['phone']='';//授权手机号
        $add_user1['old_agent_id']='';//旧的经纪人id
        $user1_id=db('company_user')->insertGetId($add_user1);//潜在客户
        $add_user2['company_id']=$company_id;//公司id
        $add_user2['agent_id']=$agent_id;//经纪人id
        $add_user2['unionid']='';//unionid
        $add_user2['openid']='';//小程序openid
        $add_user2['nickname']='5bCP5Y2O';//昵称
        $add_user2['cover']='';//头像
        $add_user2['itime_potential']=strtotime('-1 day');//潜在客户时间
        $add_user2['daytime_potential']=strtotime(date('Y-m-d',strtotime('-1 day')));//潜在客户时间（y-m-d）
        $add_user2['itime_exclusive']=strtotime('-1 day');//专属客户时间
        $add_user2['daytime_exclusive']=strtotime(date('Y-m-d',strtotime('-1 day')));//专属客户时间（y-m-d）
        $add_user2['phone']='';//授权手机号
        $add_user2['old_agent_id']='';//旧的经纪人id
        $user2_id=db('company_user')->insertGetId($add_user2);//专属客户

        //company_agent_user表数据
        $add_agent_user1['company_id']=$company_id;//公司id
        $add_agent_user1['company_shop_id']=0;//门店id
        $add_agent_user1['agent_id']=$agent_id;//经纪人id
        $add_agent_user1['user_id']=$user1_id;//用户id
        $add_agent_user1['status']=1;//用户状态：0解绑客户、1潜在客户、2专属客户
        $add_agent_user1['num']=1;//互动次数
        $add_agent_user1['last_time']=strtotime('-1 day');//上次访问时间
        $add_agent_user1['phone']='';//手机号
        $add_agent_user1['remark_phone']='';//备注手机号
        $add_agent_user1['company']='';//公司名称
        $add_agent_user1['position']='';//职位
        $add_agent_user1['province']='';//省
        $add_agent_user1['city']='';//市
        $add_agent_user1['area']='';//区
        $add_agent_user1['birthday']=0;//生日
        $add_agent_user1['remark']='';//备注名
        $add_agent_user1['source']=1;//来源：1分享名片小程序、2文章获客
        $add_agent_user1['recommend_house']='';//定制需求推荐房源id集合
        $add_agent_user1['is_demand']=0;//是否填写定制需求（1已填写，0未填写）
        $add_agent_user1['itime']=strtotime('-1 day');//成为客户的时间
        $add_agent_user1['day_time']=strtotime(date('Y-m-d',strtotime('-1 day')));//成为客户的时间（y-m-d）
        $add_agent_user1['itime_potential']=strtotime('-1 day');//成为潜在客户的时间
        $add_agent_user1['daytime_potential']=strtotime(date('Y-m-d',strtotime('-1 day')));//成为潜在客户的时间（y-m-d）
        $add_agent_user1['itime_exclusive']=0;//成为专属客户的时间
        $add_agent_user1['daytime_exclusive']=0;//成为专属客户的时间（y-m-d）
        $add_agent_user1['old_agent_id']='';//旧的经纪人id
        $agent_user1_id=db('company_agent_user')->insertGetId($add_agent_user1);//潜在客户
        $add_agent_user2['company_id']=$company_id;//公司id
        $add_agent_user2['company_shop_id']=0;//门店id
        $add_agent_user2['agent_id']=$agent_id;//经纪人id
        $add_agent_user2['user_id']=$user2_id;//用户id
        $add_agent_user2['status']=2;//用户状态：0解绑客户、1潜在客户、2专属客户
        $add_agent_user2['num']=1;//互动次数
        $add_agent_user2['last_time']=strtotime('-1 day');//上次访问时间
        $add_agent_user2['phone']='';//手机号
        $add_agent_user2['remark_phone']='';//备注手机号
        $add_agent_user2['company']='';//公司名称
        $add_agent_user2['position']='';//职位
        $add_agent_user2['province']='';//省
        $add_agent_user2['city']='';//市
        $add_agent_user2['area']='';//区
        $add_agent_user2['birthday']=0;//生日
        $add_agent_user2['remark']='';//备注名
        $add_agent_user2['source']=1;//来源：1分享名片小程序、2文章获客
        $add_agent_user2['recommend_house']='';//定制需求推荐房源id集合
        $add_agent_user2['is_demand']=0;//是否填写定制需求（1已填写，0未填写）
        $add_agent_user2['itime']=strtotime('-1 day');//成为客户的时间
        $add_agent_user2['day_time']=strtotime(date('Y-m-d',strtotime('-1 day')));//成为客户的时间（y-m-d）
        $add_agent_user2['itime_potential']=strtotime('-1 day');//成为潜在客户的时间
        $add_agent_user2['daytime_potential']=strtotime(date('Y-m-d',strtotime('-1 day')));//成为潜在客户的时间（y-m-d）
        $add_agent_user2['itime_exclusive']=strtotime('-1 day');//成为专属客户的时间
        $add_agent_user2['daytime_exclusive']=strtotime(date('Y-m-d',strtotime('-1 day')));//成为专属客户的时间（y-m-d）
        $add_agent_user2['old_agent_id']='';//旧的经纪人id
        $agent_user2_id=db('company_agent_user')->insertGetId($add_agent_user2);//专属客户
        //erp_agent_user_interaction_log表数据
        $inter_log1['agent_user_id']=$agent_user1_id;//关联id
        $inter_log1['type']=1;//1名片查看、2名片点赞、3名片视频播放、4动态点赞、5查看推荐房源、6关注房源、7分享房源、8房贷测算（费用测算）、9贷款预审、10智能选房
        $inter_log1['house_id']=0;//房源id
        $inter_log1['trends_id']=0;//动态id
        $inter_log1['itime']=strtotime('-1 day');//添加时间
        db('agent_user_interaction_log')->insert($inter_log1);
        $inter_log2['agent_user_id']=$agent_user2_id;//关联id
        $inter_log2['type']=1;//1名片查看、2名片点赞、3名片视频播放、4动态点赞、5查看推荐房源、6关注房源、7分享房源、8房贷测算（费用测算）、9贷款预审、10智能选房
        $inter_log2['house_id']=0;//房源id
        $inter_log2['trends_id']=0;//动态id
        $inter_log2['itime']=strtotime('-1 day');//添加时间
        db('agent_user_interaction_log')->insert($inter_log2);
        //erp_agent_follow_log表数据(专属客户才有跟进)
        $add_follow['agent_user_id']=$agent_user2_id;//关联id
        $add_follow['remark']='5piO5aSp5pep5LiK6Z2i6LCI';//跟进内容
        $add_follow['itime']=strtotime('-1 day');//添加时间;
        $add_follow['old_id']='';//关联id
        $add_follow['old_name']='';//关联id
        db('agent_follow_log')->insert($add_follow);
        //erp_agent_trends表数据
        $ad_trends['agent_id']=$agent_id;//经纪人id
        $ad_trends['content']='5rC055S15LqR56uL5pa5LS3pvpnms4nlpKfpnaLlnLDpk4ExMDDnsbPvvIzliJrpnIDlpZfkuozlj6/mlLnlpZfkuInvvIzlpKnpuYXmuZblsI/lrabljLrmiL/vvIznjrDkvY7kuo7luILlnLrku7c0N+S4h++8jOi/hemAn+aNoea8j++8ge+8gQ==';//内容
        $ad_trends['pics']='https://oss.fpaiyun.com/android/c4ca4238a0b923820dcc509a6f75849b/dynamic/862f7a367806e9cdd455877b3f539575.jpg,https://oss.fpaiyun.com/android/c4ca4238a0b923820dcc509a6f75849b/dynamic/18ce8d7ccf8e789fa92b97b793de80d7.jpg,https://oss.fpaiyun.com/android/c4ca4238a0b923820dcc509a6f75849b/dynamic/fad33f8fa129991c3558fd3890753d00.jpg,https://oss.fpaiyun.com/android/c4ca4238a0b923820dcc509a6f75849b/dynamic/4644a29f63fb4c10604e1aac185593fa.jpg,https://oss.fpaiyun.com/android/c4ca4238a0b923820dcc509a6f75849b/dynamic/b3dc725acbf84ef27d0d852e8b1fc3b3.jpg,https://oss.fpaiyun.com/android/c4ca4238a0b923820dcc509a6f75849b/dynamic/b2623b67aaec913547ffaa650976748b.jpg,https://oss.fpaiyun.com/android/c4ca4238a0b923820dcc509a6f75849b/dynamic/0e12b51053b36880ff30786d427a220d.jpg,https://oss.fpaiyun.com/android/c4ca4238a0b923820dcc509a6f75849b/dynamic/f85919899c2ee7bd3bf2493f5943651f.jpg,https://oss.fpaiyun.com/android/c4ca4238a0b923820dcc509a6f75849b/dynamic/a4eb9a842fa469b078f41376e6ff3901.jpg';//图片
        $ad_trends['init_see_num']=0;//初始查看数
        $ad_trends['init_give_num']=0;//初始点赞数
        $ad_trends['see_num']=0;//真实点赞数
        $ad_trends['give_num']=0;//真实点赞数
        $ad_trends['itime']=strtotime('-1 day');//添加时间
        db('agent_trends')->insert($ad_trends);
        //获取token
        $Token = new Token();
        $token_ = $Token->getToken ($agent_id, $headers,Token::API_TOKEN, Token::EXPIRE_TIME, RedisKey::APP_TOKEN_HASH);
        $mainid = md5 (md5 ($agent_id));
        //参数组装
        $add_company=db('company')->where("id={$company_id}")->find();
        $city_codes=$add_company['default_city_code']?explode('-',$add_company['default_city_code']):[];
        $city_code=isset($city_codes[0])?$city_codes[0]:'';
        $city_name=isset($city_codes[1])?$city_codes[1]:'';
        $region=db('region')->field('x(location) as lng,Y(location) as lat')->where("city_code={$city_code}")->find();
        $re=['token' => $token_,
            'avatar' => empty($avatar) ? config('global.default_avt') : $avatar,//头像
            'account' => $params['phone'],
            'id' => $mainid,
            'is_push' => 1,
            'is_demand' => 0,
            'city_code'=>$city_code,
            'city_name'=>$city_name,
            'company_id'=>$company_id,
            'agent_id'=>$agent_id,//
            'lng'=>$region['lng'],
            'lat'=>$region['lat'],
            'applets_id'=>$add_company['applets_id'],
            'com_id'=>$add_company['wechat_appid'],
            'com_key'=>$add_company['wechat_secret'],
            'en_key'=>$add_agent['en_key']
        ];

        return $re;

    }

    /**
     * 生成二维码
     */
    public static function createWechatCode($company_id, $id) {
        $url = '';
        $company=db('company')->field('appid,secret')->where("id={$company_id} and deleted=0")->find();
        $appid = $company['appid'];
        $secret = $company['secret'];
        $grant_type = 'client_credential';
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type={$grant_type}&appid={$appid}&secret={$secret}";
        $json = self::httpRequest($access_token);
        $json = json_decode($json, true);
        if (!isset($json['access_token'])) {
            return false;
        }
        $ACCESS_TOKEN = $json["access_token"];
        $qcode = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$ACCESS_TOKEN}";
        $param = json_encode(array("path" => "pages/index/index?agent_id={$id}", "width" => 150));
        $result = self::httpRequest($qcode, $param, "POST");//文件流
        $oss = Oss::getInstance();
        $url = $oss->createFilename("badmin/createWechatCode", 'jpeg');
        if(config('global.dev') == 'dev'){
            $url = $oss->createFilename("test/badmin/createWechatCode", 'jpeg');
        }
        if ($oss->putObject($result)) {
            $redisModel = Redis::getInstance();
            $redisModel->hset('upload_file', date('Y-m-d'), "badmin/createWechatCode");
        }

        return $url;
    }

    /**
     * http请求
     * @param $url
     * @param string $data
     * @param string $method
     * @return bool|string
     */
    public static function httpRequest($url, $data = '', $method = 'GET') {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if ($method == 'POST') {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '') {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

}
